﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DeviceControlServer.ServerBase;
using DeviceCommon;
using LogLib;

namespace DeviceControlServer.ClientCommands
{
    public class Exit : ClientRequestPackCommand<RequestMsgPackge>
    {
        public IDevice Device = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public DeviceServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, RequestMsgPackge pack)
        {
            Session = session;
            Server = session.AppServer as DeviceServer;
            Server.OnNewSessionRequestReceived(session, pack);
            if (!Server.Devices.ContainsKey(pack.DeviceName))
            {
                Log.WriteAsync("不存在的设备:" + pack.DeviceName);
                return;
            }
            Device = Server.Devices[pack.DeviceName];
            if (Device == null)
            {
                Log.WriteAsync("设备对象为空:" + pack.DeviceName);
                return;
            }
            string outstring = "";
            try
            {
                Device.Exit(pack.InParams, out outstring);
                if (Device.Exited)
                {
                    OnExitOK(outstring);
                }
                else
                {
                    OnExitFailed(Device.ErrorMessage, outstring);
                }
            }
            catch (Exception ex)
            {
                Server.OnCatchException(session, Device, DeviceAction.Init, ex);
                return;
            }
        }

        protected void OnExitOK(string outParams)
        {
            ResponseMsgPackge pack = new ResponseMsgPackge(Device.Name, DeviceAction.Exit);
            pack.Success = true;
            pack.Message = "";
            pack.ActionState = DeviceActionState.ExitOK;
            pack.SetParams(outParams);
            Session.Send(pack);
            Server.ReportDeviceReponse(pack);
        }

        protected void OnExitFailed(string reasonMsg, string outParams)
        {
            ResponseMsgPackge pack = new ResponseMsgPackge(Device.Name, DeviceAction.Exit);
            pack.Success = true;
            pack.Message = reasonMsg;
            pack.ActionState = DeviceActionState.ExitFailed;
            pack.SetParams(outParams);
            Session.Send(pack);
            Server.ReportDeviceReponse(pack);
        }
    }
}
